package com.kplzj.maptest.map;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import com.kplzj.maptest.map.customView.CarBean;

import java.util.ArrayList;
import java.util.List;

    public class CarPathView extends View {
        private List<PointF> points; // 存储点的列表
        private Paint paint; // 用于绘制的画笔

        // 构造函数
        public CarPathView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }

        // 初始化方法，设置画笔等
        private void init() {
            points = new ArrayList<>();
            paint = new Paint();
            paint.setColor(0xFF000000); // 设置画笔颜色为黑色
            paint.setStrokeWidth(1); // 设置画笔宽度
            paint.setStyle(Paint.Style.STROKE); // 设置画笔样式为线条

        }

        public void setPoints(List<CarBean> carBeans){

            for (CarBean bean : carBeans) {
                points.add(new PointF(bean.getX(), bean.getY()));
            }
            invalidate();
        }

        // 重写onDraw方法
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            // 如果点不足以形成线条，则不绘制
            if (points.size() < 2) return;

//            // 移动画布起始点，并保存状态
            canvas.save();
            canvas.translate(0, 0);

            // 绘制点集中的所有线段
            for (int i = 0; i < 23 - 1; i++) {
                PointF startPoint = points.get(i);
                PointF endPoint = points.get(i + 1);
                canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
            }

            // 如果有至少24个点，连接第24个点和第一个点
            if (points.size() > 23) {
                PointF firstPoint = points.get(0);
                PointF lastPoint = points.get(23);
                canvas.drawLine(firstPoint.x, firstPoint.y, lastPoint.x, lastPoint.y, paint);
            }

            // 恢复画布状态
            canvas.restore();
        }

        // 点的内部类，用于存储坐标
        private class PointF {
            float x;
            float y;

            PointF(float x, float y) {
                this.x = x;
                this.y = y;
            }
        }

}
